const express = require("express");
const router = express.Router();
const db = require("../models");
const verify = require("../tools/verifyToken");

router.get("/all", verify, (req, res) => {
  console.log(req.ip);
  db.Project.findAll({ include: ["Client", "manager"] }).then((projects) =>
    res.send(projects)
  );
});

router.get("/get_by_id", verify, (req, res) => {
  db.Project.findOne({
    where: {
      id: req.query.id,
    },
  })
    .then((project) => {
      res.send(project);
    })
    .catch((err) => {
      res.status(400).send({ msg: err.message });
    });
});

router.get("/to_be_censored", verify, (req, res) => {
  // console.log('hi');
  // console.log(req.query);
  const checkerId = req.query.checkerId;
  const status = req.query.status;
  db.Project.findAll({
    where: {
      checker_id: checkerId,
      approval_status: status,
    },
    include: ["Client", "manager"],
  })
    .then((projects) => {
      res.send(projects);
    })
    .catch((err) => {
      res.status(400).send({ msg: err.message });
    });
});

router.post("/add", verify, (req, res) => {
  const project = req.body;
  console.log(project);
  // if(!project.id)
  //     project.id = Math.floor(Math.random()*1000000+1)
  db.Project.create(project)
    .then((project) => {
      res.send(project);
    })
    .catch((err) => {
      res.status(400).send(err);
    });
});

router.post("/delete", verify, (req, res) => {
  db.Project.destroy({
    where: {
      id: req.body.id,
    },
  })
    .then((n) => {
      res.send({ deleted: n });
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/edit", verify, (req, res) => {
  db.Project.update(req.body, {
    where: {
      id: req.body.id,
    },
  })
    .then((n) => {
      res.send({ updated: n });
    })
    .catch((err) => {
      res.send(err);
    });
});
module.exports = router;
